﻿using Xenta.Events;

namespace Xenta.Triggers
{
    /// <summary>
    /// Exposes the trigger interface.
    /// </summary>
    /// <remarks>
    /// The trigger is used in the eventing system. 
    /// All triggers will be attached to an 
    /// event broker within infrastructure instantiating 
    /// process.
    /// </remarks>
    public interface ITrigger : IDependency
    {
        #region Methods
        
        /// <summary>
        /// Attaches the trigger to an event broker.
        /// </summary>
        /// <param name="eventBroker">The event broker.</param>
        void Attach(IEventBroker eventBroker);

        /// <summary>
        /// Detaches the trigger from an event broker;
        /// </summary>
        /// <param name="eventBroker">The event broker.</param>
        void Detach(IEventBroker eventBroker);

        #endregion
    }

    /// <summary>
    /// Represents the trigger class.
    /// </summary>
    public abstract class Trigger<TEvent> : ITrigger
        where TEvent : IEvent
    {
        #region Methods

        /// <summary>
        /// Attaches the trigger to an event broker.
        /// </summary>
        /// <param name="eventBroker">The event broker.</param>
        public virtual void Attach(IEventBroker eventBroker)
        {
            if(eventBroker != null)
                eventBroker.Subscribe<TEvent>(Handler);
        }

        /// <summary>
        /// Detaches the trigger from an event broker.
        /// </summary>
        /// <param name="eventBroker">The event broker.</param>
        public virtual void Detach(IEventBroker eventBroker)
        {
            if(eventBroker != null)
                eventBroker.Unsubscribe<TEvent>(Handler);
        }

        #endregion

        #region Utilities

        /// <summary>
        /// Handles an event.
        /// </summary>
        /// <param name="evt">The event.</param>
        protected abstract void Handler(TEvent evt);

        #endregion
    }
}
